package com.syezon.wifikey.home.viewmodel;

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.MutableLiveData;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.support.annotation.NonNull;

import com.syezon.android.base.utils.ActivityUtils;
import com.syezon.wifikey.utils.GpsUtil;
import com.syezon.wifikey.utils.Utils;
import com.syezon.wifikey.wifi.WifiSupport;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by Administrator on 2018/9/7.
 */

public class SwitchViewModel extends AndroidViewModel {

    MutableLiveData<Boolean> wifiStateLiveData;
    MutableLiveData<Boolean> airModeLiveData;
    MutableLiveData<Boolean> gpsModelLiveData;
    MutableLiveData<Boolean> dataSwitchListData = new MutableLiveData<>();
    private WifiStateReceiver wifiStateReceiver;
    private AirModeReceiver airModeReceiver;
    private GPSStateReceiver gpsStateReceiver;

    public SwitchViewModel(@NonNull Application application) {
        super(application);
    }


    public MutableLiveData<Boolean> getWifiStateLiveData() {
        if (wifiStateLiveData == null) {
            wifiStateLiveData = new MutableLiveData<>();
            registerWifiStateReceiver();
        }
        return wifiStateLiveData;
    }

    public MutableLiveData<Boolean> getAirModeLiveData() {
        if (airModeLiveData == null) {
            airModeLiveData = new MutableLiveData<>();
            registerAirModeReceiver();
        }
        return airModeLiveData;
    }

    public MutableLiveData<Boolean> getGpsLiveData() {
        if (gpsModelLiveData == null) {
            gpsModelLiveData = new MutableLiveData<>();
            registerGpsReceiver();
        }
        return gpsModelLiveData;
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        unRegisterWifiStateReceiver();
        unRegisterAirModeReceiver();
        unRegisterGpsReceiver();
    }

    public void registerWifiStateReceiver() {
        if (wifiStateReceiver == null) {
            wifiStateReceiver = new WifiStateReceiver();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        getApplication().registerReceiver(wifiStateReceiver, intentFilter);
    }

    public void unRegisterWifiStateReceiver() {
        if (wifiStateReceiver != null) {
            getApplication().unregisterReceiver(wifiStateReceiver);
        }
    }

    public void unRegisterGpsReceiver() {
        if (gpsStateReceiver != null) {
            getApplication().unregisterReceiver(gpsStateReceiver);
        }
    }

    public void registerGpsReceiver() {
        if (gpsStateReceiver == null) {
            gpsStateReceiver = new GPSStateReceiver();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocationManager.MODE_CHANGED_ACTION);
        getApplication().registerReceiver(gpsStateReceiver, intentFilter);
    }

    public void toggleMobileData(Context context, boolean enable) {
        ConnectivityManager connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        Class<?> connectivitymanagerclass = null;
        Field connectivitymanagerfield = null;
        Class<?> iconnectivitymanagerclass = null;
        Object iconnectivitymanagerobject = null;
        Method setMobileDataEnabledMethod = null;
        try {
            connectivitymanagerclass = Class.forName(connManager.getClass()
                    .getName());
            connectivitymanagerfield = connectivitymanagerclass
                    .getDeclaredField("mService");
            connectivitymanagerfield.setAccessible(true);

            iconnectivitymanagerobject = connectivitymanagerfield
                    .get(connManager);
            iconnectivitymanagerclass = Class
                    .forName(iconnectivitymanagerobject.getClass().getName());

            setMobileDataEnabledMethod = iconnectivitymanagerclass
                    .getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
            setMobileDataEnabledMethod.setAccessible(true);

            setMobileDataEnabledMethod.invoke(iconnectivitymanagerobject, enable);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public boolean isMobileDataEnable() {
        ConnectivityManager cm = (ConnectivityManager) Utils.getApp().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        Class cmClass = cm.getClass();
        Class[] argClasses = null;
        Object[] argObject = null;
        Boolean isOpen = false;
        try {
            Method method = cmClass.getMethod("getMobileDataEnabled", argClasses);
            isOpen = (Boolean) method.invoke(cm, argObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isOpen;
    }

    /**
     * 打开网络共享与热点设置页面
     */
    public void openAPUI() {
        try {
            Intent intent = new Intent();
            //直接打开热点设置页面（不同ROM有差异）
            ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.Settings$TetherSettingsActivity");
            //下面这个是打开网络共享与热点设置页面
            //ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.TetherSettings");
            intent.setComponent(comp);
            ActivityInfo activityInfo = intent.resolveActivityInfo(Utils.getApp().getPackageManager(), PackageManager.MATCH_DEFAULT_ONLY);
            if (activityInfo != null) {
                ActivityUtils.startActivity(intent);
            }
        } catch (Exception e) {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_SETTINGS);
            ActivityUtils.startActivity(intent);
        }

    }

    /**
     * 判断是否已打开WiFi热点
     *
     * @return
     */
    public boolean isWifiApEnabled() {
        boolean isOpen = false;
        try {
            WifiManager wifiManager = (WifiManager) Utils.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            if (wifiManager == null) {
                return false;
            }
            Method method = wifiManager.getClass().getMethod("isWifiApEnabled");
            isOpen = (boolean) method.invoke(wifiManager);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return isOpen;
    }

    public boolean isWifiStateEnable(){
        return WifiSupport.isWifiEnable();
    }

    public boolean isGpsEnable(){
       return GpsUtil.isOPen();
    }

    public boolean isAirPlaneEnable() {
        boolean isOn = false;
        try {
            int isAirplaneMode = Settings.System.getInt(Utils.getApp().getContentResolver(),
                    Settings.System.AIRPLANE_MODE_ON, 0);
            isOn = (isAirplaneMode == 1) ? true : false;
        } catch (Exception e) {
        }
        return isOn;
    }


    public void registerAirModeReceiver() {
        if (airModeReceiver == null) {
            airModeReceiver = new AirModeReceiver();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        getApplication().registerReceiver(airModeReceiver, intentFilter);
    }

    public void unRegisterAirModeReceiver() {
        if (airModeReceiver != null) {
            getApplication().unregisterReceiver(airModeReceiver);
        }
    }

    public class AirModeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
                int isAirplaneMode = Settings.System.getInt(context.getContentResolver(),
                        Settings.System.AIRPLANE_MODE_ON, 0);
                boolean isOn = (isAirplaneMode == 1) ? true : false;
                if (isOn) {
                    getAirModeLiveData().setValue(true);
                } else {
                    getAirModeLiveData().setValue(false);
                }
            }
        }
    }

    public class WifiStateReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
                int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
                if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
                    if (wifiStateLiveData != null) {
                        wifiStateLiveData.postValue(true);
                    }
                }
                if (wifiState == WifiManager.WIFI_STATE_DISABLED) {
                    if (wifiStateLiveData != null) {
                        wifiStateLiveData.postValue(false);
                    }
                }
            }
        }
    }

    public class GPSStateReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (LocationManager.MODE_CHANGED_ACTION.equals(action)) {
                boolean oPen = GpsUtil.isOPen();
                if (oPen) {
                    getGpsLiveData().setValue(true);
                } else {
                    getGpsLiveData().setValue(false);
                }
            }
        }
    }
}
